const express = require('express')
const createJWT = require('../utils/jwt')
const db = require('../utils/db')
const router = express.Router()
const sendMail = require('../utils/mail')
//所有导航
const NavList = [
  { title: '经营概况', icon: 'AccountBookOutlined', path: '/Home' },
  { title: '新开就诊', icon: 'FileAddOutlined', path: '/Home/NewVisit' },
  {
    title: '挂号管理',
    icon: 'CheckSquareOutlined',
    children: [
      { title: '新增挂号', path: '/Home/RegisteredAdd' },
      { title: '挂号记录', path: '/Home/Registered' }
    ]
  },
  { title: '药品零售', icon: 'ShoppingOutlined', path: '/Home/RetailMedicine' },
  {
    title: '收费管理',
    icon: 'MoneyCollectOutlined',
    path: '/Home/ChargeManagement'
  },
  { title: '患者管理', icon: 'TeamOutlined', path: '/Home/PatientManagement' },
  {
    title: '药品管理',
    icon: 'MedicineBoxOutlined',
    children: [
      { title: '药品调价', path: '/Home/pricing' },
      { title: '药品信息维护', path: '/Home/DrugInformation' }
    ]
  },
  {
    title: '统表管理',
    icon: 'AreaChartOutlined',
    children: [
      { title: '药品统计', path: '/Home/DrugStatistics' },
      { title: '患者统计', path: '/Home/PatienStatistics' },
      { title: '收费统计', path: '/Home/ChargeStatistics' }
    ]
  },
  {
    title: '系统管理',
    icon: 'SettingOutlined',
    children: [
      { title: '费用设置', path: '/Home/ExpensesSetting' },

      { title: '员工管理', path: '/Home/EmployeesManagement' }
    ]
  }
]
//生成导航
function createPower(power) {
  return NavList.filter(v => power.includes(v.title))
}
//登录
router.post('/login', (req, res) => {
  const { email, password } = req.body
  //登录逻辑
  let sql = `SELECT * FROM role JOIN doctor  WHERE u_email='${email}' AND u_password='${password}' AND u_r_id=r_id AND u_isDel=0 AND u_status=1;`
  db.query(sql, (err, data) => {
    if (err) {
      res.send({ error: 1, msg: '数据库查询失败', err })
    } else {
      if (data.length) {
        const token = createJWT({ email }, '7d')
        console.log(data[0])
        res.send({
          error: 0,
          userData: {
            u_id: data[0].u_id,
            u_name: data[0].u_name,
            u_sex: data[0].u_sex,
            u_age: data[0].u_age,
            u_tel: data[0].u_tel,
            u_r_id: data[0].u_r_id,
            u_createTime: data[0].u_createTime,
            u_status: data[0].u_status,
            u_email: data[0].u_email,
            u_cardID: data[0].u_cardID,
            u_address: data[0].u_address,
            u_password: data[0].u_password
          },
          token,
          msg: '登录成功',
          power: createPower(data[0].r_power)
        })
      } else {
        res.send({ error: 1, msg: '邮箱或密码不正确' })
      }
    }
  })
})
//找回密码，发送验证码
router.post('/getCode', (req, res) => {
  const code = Math.random().toString().slice(2, 8)

  const { email } = req.body
  sendMail(email, code)
    .then(() => {
      let sql = `insert into mail_code (email,code,create_time) values('${email}',${code},${Date.now()}) on duplicate key update code=values(code),create_time=values(create_time);`
      db.query(sql, err => {
        if (err) {
          res.send({
            error: 1,
            msg: '数据库存储失败',
            errInof: err
          })
        } else {
          res.send({
            error: 0,
            msg: '验证码发送成功，有效期10分钟，未收到邮件请检查垃圾箱'
          })
        }
      })
    })
    .catch(err => {
      res.send({
        error: 1,
        msg: '发送失败',
        errInof: err
      })
    })
})
//找回密码
router.post('/resetPwd', (req, res) => {
  const { email, newPwd, inpCode } = req.body
  const checkCode = `SELECT code,create_time AS time FROM mail_code WHERE email='${email}';`
  const resetPwd = `update doctor set u_password='${newPwd}' WHERE u_email='${email}';`
  db.query(checkCode, (err, data) => {
    if (err) {
      res.send({ error: 1, msg: '数据库查询失败', err })
    } else {
      if (data.length) {
        const { code, time } = data[0]
        if (Date.now() - time > 1000 * 60 * 10) {
          //验证码过期
          res.send({
            error: 1,
            msg: '验证码过期，请重新获取'
          })
        } else if (code == inpCode) {
          //验证码正确
          //清除code避免重复利用
          db.query(`DELETE FROM mail_code WHERE email='${email}';`)
          db.query(resetPwd, err => {
            if (err) {
              res.send({
                error: 1,
                msg: '未知错误',
                errInfo: err
              })
            } else {
              res.send({
                error: 0,
                msg: '密码修改成功，请继续登录'
              })
            }
          })
        } else {
          res.send({
            error: 1,
            msg: '验证码错误'
          })
        }
      } else {
        res.send({
          error: 1,
          msg: '验证码错误'
        })
      }
    }
  })
})
//修改密码
router.post('/repwd', (req, res) => {
  const { email, oldPwd, newPwd } = req.body
  const check = `SELECT * FROM doctor WHERE u_email = '${email}' AND u_password = '${oldPwd}';`
  const resetSql = `UPDATE clinic.doctor SET u_password = '${newPwd}' WHERE u_email = '${email}';`
  db.query(check, (err, data) => {
    if (err) {
      res.send({
        error: 1,
        msg: '数据库查询失败',
        err
      })
    } else if (data.length === 0) {
      res.send({
        error: 1,
        msg: '旧密码输入错误'
      })
    } else {
      db.query(resetSql, err => {
        if (err) {
          res.send({
            error: 1,
            msg: '数据库查询失败',
            err
          })
        } else {
          res.send({
            error: 0,
            msg: '修改成功'
          })
        }
      })
    }
  })
})
module.exports = router
